package com.audaque.jadmin.common.utils;

import java.lang.reflect.Field;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.apache.commons.lang3.reflect.FieldUtils;

import com.audaque.jadmin.system.model.User;

/**
 * @Description :
 * @FileName: ReflectUtils.java
 * @Author :WeiHui.Zhang
 * @Data : 2015年10月27日 下午2:58:51
 * @Version:V1.00
 */
public class ReflectUtils {

	public static void main(String[] args) {
		User user = new User();
		user.setUserAccount("zhang");

		System.out.println(getFieldValue(user, ""));
	}

	public static Object getFieldValue(final Object cls, final String fieldName) {
		Validate.isTrue(cls != null, "The class must not be null");
		Validate.isTrue(StringUtils.isNotBlank(fieldName), "The field name must not be blank/empty");
		Object result = null;
		Field field = FieldUtils.getDeclaredField(cls.getClass(), fieldName, true);
		try {
			if (field != null) {
				result = field.get(cls);
			}
		} catch (IllegalArgumentException | IllegalAccessException e) {
			e.printStackTrace();
		}
		return result;
	}

	public static Field getField(Object obj, String fieldName) {
		Field field = null;
		for (Class<?> clazz = obj.getClass(); clazz != Object.class; clazz = clazz.getSuperclass()) {
			try {
				field = clazz.getDeclaredField(fieldName);
				break;
			} catch (NoSuchFieldException e) {
				// 这里不用做处理，子类没有该字段可能对应的父类有，都没有就返回null。
			}
		}
		return field;
	}
}
